<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\Api\LikesRequest;
use App\Models\CommentsLike;
use App\Models\News;
use App\Models\NewsCollects;
use App\Models\NewsLike;
use App\Models\Posts;
use App\Models\PostsCollects;
use App\Models\PostsLike;
use App\Transformers\NewsTransformer;
use App\Transformers\PostsTransformer;
use Illuminate\Http\Request;

class LikesController extends Controller
{
    public function index(Request $request, $type)
    {
        if ($type == 'news') {
            $news_ids = NewsCollects::where('user_id', $this->user->id)->pluck('news_id');

            $data = News::whereIn('id', $news_ids)->paginate();

            return $this->response->paginator($data, new NewsTransformer());
        }

        if ($type == 'posts') {
            $posts_id = PostsCollects::where('user_id', $this->user->id)->pluck('posts_id');

            $data = Posts::whereIn('id', $posts_id)->paginate();

            return $this->response->paginator($data, new PostsTransformer());
        }
    }

    public function create(LikesRequest $request)
    {
        $res = false;

        $msg = trans('api.save_succeed');

        $type = $request->get('type');

        if ($type == 'news') {
            $case = [
                'news_id' => $request->get('news_id'),
                'user_id' => $this->user->id,
            ];

            $like = NewsLike::where($case)->first();

            if (!$like) {
                $res = NewsLike::create($case);

            } else {
                $res = $like->delete();

                $msg = $res ? trans('api.cancel_succeed') : trans('api.cancel_failed');
            }
        }

        if ($type == 'posts') {
            $case = [
                'posts_id' => $request->get('posts_id'),
                'user_id' => $this->user->id,
            ];

            $like = PostsLike::where($case)->first();

            if (!$like) {
                $res = PostsLike::create($case);

            } else {
                $res = $like->delete();

                $msg = $res ? trans('api.cancel_succeed') : trans('api.cancel_failed');
            }
        }

        if ($type == 'comment') {
            $case = [
                'comment_id' => $request->get('comment_id'),
                'user_id' => $this->user->id,
            ];

            $like = CommentsLike::where($case)->first();

            if (!$like) {
                $res = CommentsLike::create($case);

            } else {
                $res = $like->delete();

                $msg = $res ? trans('api.cancel_succeed') : trans('api.cancel_failed');
            }
        }

        if ($res) {
            return response()->json(['message' => $msg, 'code' => 1, 'status' => true, 'data' => ''], 200);
        } else {
            return response()->json(['message' => trans('api.save_failed'), 'code' => 0, 'status' => false], 200);
        }
    }

}
